package com.gaofei.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gaofei.domain.Cart;
import com.gaofei.domain.CartVo;
import com.gaofei.domain.HgUser;
import com.gaofei.domain.Sku;
import com.gaofei.domain.Spec;
import com.gaofei.domain.SpecOption;
import com.gaofei.domain.Spu;
import com.gaofei.service.SkuService;
import com.gaofei.service.SpecService;
import com.gaofei.service.SpuService;
import com.gaofei.service.UserService;
import com.gaofei.utils.SendMsgUtil;

@Controller
public class UserController {
	
	@Reference
	SpuService spuService;
	
	@Reference
	SpecService specService;
	
	@Reference
	SkuService skuService;
	
	@Reference
	UserService userService;
	
	@Autowired
	RedisTemplate redisTemplate;
	
	//跳转购物车列表页面
	@RequestMapping("toCart")
	public String toCart(HttpServletRequest req,Model m) {
		
		//查询购物车列表,根据用户的id,来查询用户下的购物车列表
		HgUser user = (HgUser) req.getSession().getAttribute("dbUser");//如果是用的redis解决的session共享,从redis中获取对用的用户信息(key是从cookie中来的)
		if(user!=null) {
			List<CartVo> list = userService.findCartListByUid(user.getUid());
			m.addAttribute("carts", list);
			return "cart";
			
		}
		return "login";
	}
	
	
	//加入购物车
	@RequestMapping("addCart")
	@ResponseBody
	public String addCart(CartVo vo,HttpServletRequest req) {
		HgUser user = (HgUser) req.getSession().getAttribute("dbUser");//如果是用的redis解决的session共享,从redis中获取对用的用户信息(key是从cookie中来的)
		if(user!=null) {
			try {
				vo.setUid(user.getUid());
				vo.setCreatetime(new Date());
				vo.setUpdatetime(new Date());
				//计算购物车总价
				BigDecimal price = vo.getPrice();
				int pnum = vo.getPnum();
				BigDecimal sumTotal = price.multiply(new BigDecimal(""+pnum));
				vo.setSumTotal(sumTotal);
				userService.addCart(vo);
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
				return "fail";
			}
			
		}else {
			//没有登录
			return "noLogin";
		}
	}
	
	
	
	
	//账号密码登录
	@RequestMapping("login")
	@ResponseBody
	public boolean login(HgUser portalUser,HttpServletRequest req) {
		HgUser dbUser = userService.findUserByUsernameAndPassword(portalUser);
		if(dbUser!=null) {
			//说明正好和密码正确
			req.getSession().setAttribute("dbUser", dbUser);//
			return true;
		}else {
			return false;
		}
	}
	
	
	//跳转到账号密码登录的页面
	@RequestMapping("toLogin")
	public String toLogin() {
		return "login";
	}
	///////==============================以下是验证码登录的代码========================================
	//手机号登录的方法
	/*@RequestMapping("login")
	@ResponseBody
	public boolean login(HgUser portalUser,HttpServletResponse resp) {
		//1.用户输入的信息:手机号,去数据库中查询,如果有说明有
		
		HgUser dbUser = userService.findUserByTelephone(portalUser);
		
		
		//从redis中获取验证码
		String redisCode = (String) redisTemplate.opsForValue().get("hgshop_"+portalUser.getTelephone());
		System.err.println(redisCode);
		System.err.println(portalUser.getCode()+"============");
		//2.判断dbUser是否存在,如果存在,说明该用户已经注册,开始验证验证码的合法性
		if(dbUser!=null&&portalUser.getCode().equals(redisCode)) {
//			登录成功
			//1.把用户信息保存到redis(相当于之前的session)一份
			redisTemplate.opsForValue().set(dbUser.getUid()+"", dbUser);
			//2.把用户的id或者是随机生成一个id,响应到cookie,就是为了识别是哪个用户登录的
			Cookie cookie = new Cookie("hg_user_cookie", dbUser.getUid()+"");
			resp.addCookie(cookie);
			//3.跳转到首页
			return true;
		}
		//3.否则提示,先注册
		return false;
	}*/
	//发送验证码
	@RequestMapping("sendCode")
	@ResponseBody
	public boolean sendCode(HgUser user) {
		if(user!=null&&user.getTelephone()!=null&&user.getTelephone()!="") {
			int randomCode = new Random().nextInt(9999);
			//方案1.在分布式集群环境下,存session是不可取的-==>分布式session共享的问题
			//方案2.使用redis作为验证码的存储方式
			redisTemplate.opsForValue().set("hgshop_"+user.getTelephone(), randomCode+"");
			redisTemplate.expire("hgshop_"+user.getTelephone(), 60, TimeUnit.SECONDS);//为验证码设置过期时间
			//发送短信
			SendMsgUtil.send(user.getTelephone(),randomCode);
			return true;
		}
		return false;
	}
	
	//跳转到手机验证码登录的界面
	/*@RequestMapping("toLogin")
	public String toLogin() {
		return "login4phonenum";
	}*/
	
///////================================以上是验证码登录的代码======================================
	
	
	@RequestMapping("goodsDetail")
	public String goodsDetail(Integer spuId,Model m) {
		
		Spu spu = spuService.findSpuById(spuId);
		
		//根据spu下skuList中的任意一个sku的Id查询该sku所有的规格
		List<Sku> skuList = spu.getSkuList();
		if(skuList!=null && skuList.size()!=0) {
			Sku sku = skuList.get(0);
			//根据该sku的Id查询sku下所属的规格,并且展示到详情页
			List<Spec> specs = specService.findSpecBySkuId(sku.getId());
			System.err.println(specs);
			m.addAttribute("specs", specs);
		}
		m.addAttribute("spu", spu);
		return "goodsDetail";
	}
	
	@RequestMapping("goodsx")
	@ResponseBody
	
	public List<Sku> goodsx(Integer spuId) {
		//根据spuId查询sku的集合
		List<Sku> skus = skuService.findSkuBySpuId(spuId);
		for (Sku sku : skus) {
			List<SpecOption> optionList = skuService.findOptionBySkuId(sku.getId());
			sku.setOptionList(optionList);
		}
		return skus;
		
	}
}
